﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MiniExcelLibs;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows;
using Zo.ExcelBox.Base;
using Zo.ExcelBox.Models;
using static System.Data.Entity.Infrastructure.Design.Executor;

namespace Zo.ExcelBox.ViewModels
{
    /// <summary>
    /// 
    /// </summary>
    public partial class JudicialCaseTransactionRecordVM : ObservableObject
    {
        /// <summary>
        /// 
        /// </summary>
        private ObservableCollection<JudicialCaseTransactionRecordRes> _tableDatas;

        /// <summary>
        /// 数据数量
        /// </summary>
        public ObservableCollection<JudicialCaseTransactionRecordRes> TableDatas
        {
            get => _tableDatas;
            set => SetProperty(ref _tableDatas, value);
        }

        private int _pageIndex = 1;
        /// <summary>
        /// 模版名称
        /// </summary>
        public int PageIndex
        {
            get => _pageIndex;
            set => SetProperty(ref _pageIndex, value);
        }

        private int _pageSize = 20;
        /// <summary>
        /// 每页的数据量
        /// </summary>
        public int PageSize
        {
            get => _pageSize;
            set => SetProperty(ref _pageSize, value);
        }

        private int _maxPageCount = 0;
        /// <summary>
        /// 最大页数
        /// </summary>
        public int MaxPageCount
        {
            get => _maxPageCount;
            set => SetProperty(ref _maxPageCount, value);
        }



        private int _dataCount = 0;

        /// <summary>
        /// 数据总数量
        /// </summary>
        public int DataCount
        {
            get => _dataCount;
            set => SetProperty(ref _dataCount, value);
        }

        /// <summary>
        /// 交易户名
        /// </summary> 
        public string _accountName = string.Empty;

        /// <summary>
        /// 交易户名
        /// </summary> 
        public string AccountName
        {
            get => _accountName;
            set => SetProperty(ref _accountName, value);
        }

        /// <summary>
        /// 对手账号
        /// </summary>
        public string _counterpartyAccount = string.Empty;


        /// <summary>
        /// 对手账号
        /// </summary> 
        public string CounterpartyAccount
        {
            get => _counterpartyAccount;
            set => SetProperty(ref _counterpartyAccount, value);
        }

        /// <summary>
        /// 交易卡号
        /// </summary>

        public string _cardNumber = string.Empty;

        /// <summary>
        /// 交易卡号
        /// </summary> 
        public string CardNumber
        {
            get => _cardNumber;
            set => SetProperty(ref _cardNumber, value);
        }

        /// <summary>
        /// 对手卡号
        /// </summary>
        public string _counterpartyCardNumber = string.Empty;


        /// <summary>
        /// 对手卡号
        /// </summary> 
        public string CounterpartyCardNumber
        {
            get => _counterpartyCardNumber;
            set => SetProperty(ref _counterpartyCardNumber, value);
        }


        /// <summary>
        /// 查询最小金额
        /// </summary>
        public decimal _TransactionAmount0 = 0;
        public decimal TransactionAmount0
        {
            get => _TransactionAmount0;
            set => SetProperty(ref _TransactionAmount0, value);
        }

        /// <summary>
        /// 查询最大金额
        /// </summary>
        public decimal _TransactionAmount1 = 0;
        public decimal TransactionAmount1
        {
            get => _TransactionAmount1;
            set => SetProperty(ref _TransactionAmount1, value);
        }

        /// <summary>
        /// 交易时间 开始
        /// </summary>
        public DateTime? _transactionTime0 = null;

        /// <summary>
        /// 交易时间 开始
        /// </summary> 
        public DateTime? TransactionTime0
        {
            get => _transactionTime0;
            set => SetProperty(ref _transactionTime0, value);
        }



        /// <summary>
        /// 交易时间 结束
        /// </summary>
        public DateTime? _transactionTime1 = null;

        /// <summary>
        /// 交易时间 结束
        /// </summary> 
        public DateTime? TransactionTime1
        {
            get => _transactionTime1;
            set => SetProperty(ref _transactionTime1, value);
        }



        /// <summary>
        /// 案件信息
        /// </summary>
        public ObservableCollection<JudicialCase> judicialCases = new ObservableCollection<JudicialCase>();


        /// <summary>
        /// 案件信息
        /// </summary>
        public ObservableCollection<JudicialCase> JudicialCases
        {
            get => judicialCases;
            set => SetProperty(ref judicialCases, value);
        }


        public JudicialCase _selectJudicialCase;

        public JudicialCase SelectJudicialCase
        {
            get => _selectJudicialCase;
            set => SetProperty(ref _selectJudicialCase, value);
        }

        /// <summary>
        /// 添加页面
        /// </summary>
        public IRelayCommand OnAddCommand { get; }

        /// <summary>
        /// 修改页面
        /// </summary>
        public IRelayCommand<MapTemplate> OnUpdateCommand { get; }

        /// <summary>
        /// 删除页面
        /// </summary>
        public IRelayCommand<MapTemplate> OnDeleteCommand { get; }

        /// <summary>
        /// 分页改变
        /// </summary>
        public IRelayCommand<int> OnPageChangeCommand { get; }


        /// <summary>
        /// 搜索
        /// </summary>
        public IRelayCommand OnSearchCommand { get; }


        /// <summary>
        /// 导出表格
        /// </summary>
        public IRelayCommand OnExportExcelCommand { get; }


        /// <summary>
        /// 数据访问
        /// </summary>
        public static SqlSugarClient _db;

        /// <summary>
        /// 案件管理
        /// </summary>
        public JudicialCaseTransactionRecordVM()
        {

            OnPageChangeCommand = new RelayCommand<int>(OnPageChange);
            OnSearchCommand = new RelayCommand(OnSearch);
            _db = new DbContext().DataBase;


            var judicialCases = _db.Queryable<JudicialCase>().ToList() ?? new List<JudicialCase>();
            judicialCases.Insert(0, new JudicialCase() { Id = 0, Name = "请选择" });
            JudicialCases = new ObservableCollection<JudicialCase>(judicialCases);
            OnExportExcelCommand = new RelayCommand(OnExportExcel);
            SelectJudicialCase = judicialCases[0];

            LoadData();

        }


        /// <summary>
        /// 加载数据
        /// </summary>
        void LoadData(int page = 1)
        {
            var total = 0;
            Rows = _db.Queryable<JudicialCaseTransactionRecord>()
                .LeftJoin<JudicialCase>((w, b) => b.Id == w.JudicialCase_Id)
                .WhereIF(!string.IsNullOrWhiteSpace(AccountName), (w, b) => w.AccountName.Contains(AccountName))
                .WhereIF(!string.IsNullOrWhiteSpace(CounterpartyAccount), (w, b) => w.CounterpartyAccount.Contains(CounterpartyAccount))
                .WhereIF(!string.IsNullOrWhiteSpace(CardNumber), (w, b) => w.CardNumber.Contains(CardNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(CounterpartyCardNumber), (w, b) => w.CounterpartyCardNumber.Contains(CounterpartyCardNumber))
                .WhereIF(TransactionAmount0 > 0, (w, b) => w.TransactionAmount >= TransactionAmount0)
                .WhereIF(TransactionAmount1 > 0, (w, b) => w.TransactionAmount <= TransactionAmount1)
                .WhereIF(TransactionTime0 != null, (w, b) => w.TransactionTime.Date >= TransactionTime0.Value.Date)
                .WhereIF(TransactionTime1 != null, (w, b) => w.TransactionTime.Date <= TransactionTime1.Value.Date)
                .WhereIF(SelectJudicialCase != null && SelectJudicialCase.Id > 0, (w, b) => w.JudicialCase_Id == SelectJudicialCase.Id)
                .Select((w, b) => new JudicialCaseTransactionRecordRes()
                {

                    JudicialCaseName = b.Name,
                    Id = w.Id,
                    AccountBalance = w.AccountBalance,
                    AccountName = w.AccountName,
                    AccountNumber = w.AccountNumber,
                    AccountType = w.AccountType,
                    BankName = w.BankName,
                    BranchCode = w.BranchCode,
                    BranchName = w.BranchName,
                    CardNumber = w.CardNumber,
                    CashFlag = w.CashFlag,
                    CounterpartyAccount = w.CounterpartyAccount,
                    CounterpartyBalance = w.CounterpartyBalance,
                    CounterpartyBank = w.CounterpartyBank,
                    CounterpartyCardNumber = w.CounterpartyCardNumber,
                    CounterpartyIdNumber = w.CounterpartyIdNumber,
                    CounterpartyInternalAccount = w.CounterpartyInternalAccount,
                    CounterpartyName = w.CounterpartyName,
                    CreateDate = w.CreateDate,
                    Currency = w.Currency,
                    IdNumber = w.IdNumber,
                    InternalAccount = w.InternalAccount,
                    IP = w.IP,
                    JudicialCase_Id = w.JudicialCase_Id,
                    MAC = w.MAC,
                    Remarks = w.Remarks,
                    ReversalFlag = w.ReversalFlag,
                    SourceFileName = w.SourceFileName,
                    SuccessFlag = w.SuccessFlag,
                    Summary = w.Summary,
                    TransactionAmount = w.TransactionAmount,
                    TransactionDirection = w.TransactionDirection,
                    TransactionId = w.TransactionId,
                    TransactionLocation = w.TransactionLocation,
                    TransactionLocationLat = w.TransactionLocationLat,
                    TransactionLocationLong = w.TransactionLocationLong,
                    TransactionTime = w.TransactionTime,
                    TransactionType = w.TransactionType,
                    Type = w.Type,
                    UpdateDate = w.UpdateDate
                })
                .ToPageList(page, PageSize, ref total);

            DataCount = total;

            TableDatas = new ObservableCollection<JudicialCaseTransactionRecordRes>(Rows);
            MaxPageCount = CommonHelper.CalculateTotalPages(total, PageSize);
        }


        void OnPageChange(int page)
        {
            LoadData(page);
        }

        void OnSearch()
        {
            LoadData();
        }


        List<JudicialCaseTransactionRecordRes> Rows = new List<JudicialCaseTransactionRecordRes>();

        /// <summary>
        /// 导出表格
        /// </summary>
        void OnExportExcel()
        {

            if (Rows.Count <= 0)
            {
                HandyControl.Controls.MessageBox.Show("无数据可以导出");
                return;
            }

            var name = SelectJudicialCase.Id <= 0 ? "全部" : SelectJudicialCase.Name;

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Title = "保存 Excel 文件",
                Filter = "Excel 文件 (*.xlsx)|*.xlsx",
                FileName = $"{name}_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx"
            };


            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;
                try
                {
                    // 写入 Excel 文件
                    MiniExcel.SaveAs(filePath, Rows);
                    HandyControl.Controls.MessageBox.Show("导出成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    HandyControl.Controls.MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

    }
}
